<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        list-style: none;
    }

    .box {
        width: 100px;
        height: 100px;
        background-color: aquamarine;
        margin-top: 20px;
        position: absolute;
        left: 0;
    }
</style>

<body>
    <button>移动到400</button>
    <button>移动到800</button>
    <div class="box"></div>
</body>
<script>
    var btn1 = document.getElementsByTagName('button')[0];
    var btn2 = document.getElementsByTagName('button')[1];
    var box = document.getElementsByClassName('box')[0];
    var timer = null;
    var current = box.offsetLeft;


    function animate(ele, target) {
        clearInterval(timer);
        timer = setInterval(function () {
            var step = 7;
            step = current < target ? step : -step;
            current += step;
            if (Math.abs(target - current) > Math.abs(step)) {
                ele.style.left = current + 'px';

            } else {

                clearInterval(timer);
                // console.log(2);

                ele.style.left = target + 'px';
                // console.log(3);


            }


        }, 20)
    }

    btn1.onclick = function () {
        animate(box, 400);

    }
    btn2.onclick = function () {
        animate(box, 800);

    }
</script>

</html>